name: Call building packages

on:
  workflow_call:
    inputs:
      artifact-name:
        description: "Unique name for collecting artifacts"
        required: true
        type: string
      pkg-names:
        description: "list package names to be build in json format"
        required: false
        type: string
        default: |
          ["lightning", "app", "fabric", "pytorch"]

defaults:
  run:
    shell: bash

jobs:
  init:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4
      - run: |
          mkdir dist && touch dist/.placeholder
      - name: Keep artifact
        id: keep-artifact
        run: python -c "print('DAYS=' + str(5 if '${{ github.event_name }}'.startswith('pull_request') else 0))" >> $GITHUB_OUTPUT
      - uses: actions/upload-artifact@v3
        with:
          name: ${{ inputs.artifact-name }}
          path: dist
          retention-days: ${{ steps.keep-artifact.outputs.DAYS }}

  build-packages:
    needs: init
    runs-on: ubuntu-22.04
    strategy:
      max-parallel: 1 # run sequential to prevent download/upload collisions
      matrix:
        pkg-name: ${{ fromJSON(inputs.pkg-names) }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v3
        with:
          name: ${{ inputs.artifact-name }}
          path: pypi
      - uses: actions/setup-python@v5
        with:
          python-version: 3.9

      - run: python -c "print('NB_DIRS=' + str(2 if '${{ matrix.pkg-name }}' == 'pytorch' else 1))" >> $GITHUB_ENV
      - name: Build & check package
        uses: ./.github/actions/pkg-check
        with:
          pkg-name: ${{ matrix.pkg-name }}
          nb-dirs: ${{ env.NB_DIRS }}

      - run: |
          mkdir pypi/${{ matrix.pkg-name }}
          cp dist/* pypi/${{ matrix.pkg-name }}/

      - uses: actions/upload-artifact@v3
        with:
          name: ${{ inputs.artifact-name }}
          path: pypi
